﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace Poligono.Core
{
    /// <summary>
    /// Class that contains methods that are useful during development, like conversion methods, etc.
    /// </summary>
    public class Util
    {
        /// <summary>
        /// Method that converts a given type to a type passed as parameter.
        /// 
        /// IT IS NECESSARY TO SEE IF THERE IS ANOTHER WAY TO DO THIS METHOD USING THE .NET FRAMEWORK 3.5
        /// 
        /// </summary>
        /// <typeparam name="T">Type for which the value is converted</typeparam>
        /// <returns>The same value passed as parameter but with the type passed as parameter</returns>
        public static T ChangeType<T>(object value)
        {
            Type conversionType = typeof(T);
            if (conversionType == null)
            {
                throw new ArgumentNullException("Type");
            }
            if ((conversionType.IsGenericType) &&
                (conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))))
            {
                if (string.IsNullOrEmpty(value.ToString()))
                {
                    return default(T);
                }
                conversionType = Nullable.GetUnderlyingType(conversionType);
            }
            return (T)Convert.ChangeType(value, conversionType);
        }

        /// <summary>
        /// Method that adds a '%' at the end of the value passed as parameter
        /// </summary>
        /// <param name="value">String to be formatted</param>
        /// <returns>Formatted value</returns>
        public static string LikeFormat(string value)
        {
            if(!value.Contains("%"))
                return value + "%";
            return value;
        }

        /// <summary>
        /// Method that encrypts a string passed as parameter
        /// </summary>
        /// <param name="value">Value to be encrypted</param>
        /// <returns>encrypted value</returns>
        public static string Encrypt(string value)
        {
            MD5CryptoServiceProvider valueEncrypted = new MD5CryptoServiceProvider();
            byte[] bs = Encoding.UTF8.GetBytes(value);
            bs = valueEncrypted.ComputeHash(bs);
            StringBuilder s = new StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string password = s.ToString();
            return password;
        }
    }
}